clear all
set more off

// -----------------------------------------------------------------------------
// Estimating the ATT with margins
// -----------------------------------------------------------------------------

// data from wooldridge
use staggered_6, clear

// cohort = final treatment duration
egen cohort = sum(w), by(id)

// current treatment duration duration 
bysort id: gen dur = sum(w)

xtset id year

// cohort*duration specification and ATT
areg logy i.year ibn.dur#ibn.cohort#c.w, absorb(id)
margins, dydx(w) subpop(if w==1)

// using xtreg instead
xtreg logy i.year ibn.dur#ibn.cohort#c.w, fe
margins, dydx(w) subpop(if w==1)

// duration-specific effects (event study)
margins, dydx(w) subpop(if dur==1)
margins, dydx(w) subpop(if dur==2)
margins, dydx(w) subpop(if dur==3)



// -----------------------------------------------------------------------------
// Demonstrating that this is the same as manual aggregation
// -----------------------------------------------------------------------------

// generate the weights
local sum=0
forvalues c=1/3 {
  forvalues p=1/3 {
			gen cp_`c'`p'=(cohort==`c' & dur==`p')
			gen dcp_`c'`p'=(cohort==`c' & dur==`p' & w)
			sum cp_`c'`p' if w
			local cp_`c'`p'=`r(mean)'
			local sum = `sum' + `r(mean)'
			di `terms'
	}
}
di `sum'

// run the regression
areg logy i.year dcp_*, absorb(id)

// aggregate the effects
local terms
forvalues c=1/3 {
  forvalues p=1/3 {
			local terms `terms' + `cp_`c'`p''*_b[dcp_`c'`p']
			//di `terms'
	}
}

lincom `terms'

